package com.yazi.mxz.gather.main.goods;

import java.io.IOException;
import java.net.SocketException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;


import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.util.EntityUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.yazi.mxz.gather.common.App;
import com.yazi.mxz.gather.common.App.PicObject;
import com.yazi.mxz.gather.entity.enums.ProcessType;
import com.yazi.mxz.gather.entity.http.JgmallResBody;
import com.yazi.mxz.gather.entity.http.JgmallResBody.Li;
import com.yazi.mxz.gather.entity.repository.ProcessLog;
import com.yazi.mxz.gather.entity.repository.Product;
import com.yazi.mxz.gather.repository.ProcessLogRepository;
import com.yazi.mxz.gather.repository.ProductRepository;

/**
 * 俊哥商城
 * http://www.jgmall.cn
 * @author mo_yq5
 * @date 2015-8-10
 */
public class JgmallCn extends Thread {
	
	CloseableHttpAsyncClient httpclient;
	ProcessLogRepository logRepository;
	ProductRepository productRepository;
	ObjectMapper om;
	
	public JgmallCn() {
		init();
	}
	
	public JgmallCn(int startPage, int endPage) {
		init();
		ProcessLog log = logRepository.findOne(ProcessType.JGMALL.ordinal());
		if (null == log) {
			log = new ProcessLog();
			log.setId(ProcessType.JGMALL.ordinal());
			log.setCur((long)startPage);
			log.setEnd((long)endPage);
			log.setCount(0);
			logRepository.insert(log);
		} else {
			log.setCur((long)startPage);
			log.setEnd((long)endPage);
			logRepository.save(log);
		}
	}
	

	public void init() {
		
		productRepository = App.context.getBean(ProductRepository.class);
		logRepository = App.context.getBean(ProcessLogRepository.class);
		
		httpclient = HttpAsyncClients.createDefault();
		httpclient.start();
		
		om = new XmlMapper();
		om.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
	}

	@Override
	public void run() {
		
		ProcessLog log = logRepository.findOne(ProcessType.JGMALL.ordinal());
		if (null == log) {
			System.out.println(ProcessType.JGMALL + "日志不存在");
			return;
		}
		
		boolean isContinue = false;
		
		try {
			
			
			while (true) {
				
				if (log.getCur() > log.getEnd()) {
					isContinue = false;
					break;
				}
				
				barcodeInfo(log.getCur());
				
				log.setCur(log.getCur() + 1);
				logRepository.save(log);
			
				sleep(200);
			}
			
		} catch (SocketException e) {
			e.printStackTrace();
			isContinue = true;
			
		} catch (Exception e1) {
			e1.printStackTrace();
			
		} 
		if (isContinue) {
			run();
		} else {
			System.out.println("执行结束！");
		}
	}
	
	private String barcodeInfo(long pageNum) throws JsonParseException, JsonMappingException,
			IOException, InterruptedException, ExecutionException {
		
		System.out.println("PageNum:" + pageNum);
		
		final HttpGet req = new HttpGet("http://www.jgmall.cn/team/goods.php?csyzg=1&page=" + pageNum);
		Future<HttpResponse> future = httpclient.execute(req, null);
		HttpResponse res = future.get();
		
		System.out.println(req.getRequestLine() + "->" + res.getStatusLine());
		
		String body = EntityUtils.toString(res.getEntity(), "utf-8");
		if (body.isEmpty()) {
			System.out.println("无响应内容!");
			return null;
		}
		
		//<ul></ul>
		String startStr = "<div class=\"good-list\" id=\"good-list\">";
		int startIndex = body.indexOf(startStr) + startStr.length();
		int endIndex = body.indexOf("</ul>", startIndex) + 5;
		body = body.substring(startIndex, endIndex);
		
		// 修改结构使能xml解析 在个别p中加b标签
		body = body.replaceAll("<p class=\"good-title\">条码:", "<p class=\"good-title\"><b>")
				.replaceAll("</p>[\\s|\\S)]{0,10}<p class=\"good-title\">规格:", "</b></p><p class=\"good-title\"><b>")
				.replaceAll("</p>[\\s|\\S)]{0,10}<br class=\"clear\" />", "</b></p>")
				.replaceAll("&nbsp;", "")// 特殊字符
				.replaceAll("&", "");// 特殊字符
		
		//System.out.println(body);
		
		JgmallResBody jgmall = om.readValue(body, JgmallResBody.class);
		List<Li> lis = jgmall.getLis();
		StringBuffer goodsInfo = new StringBuffer();
		String proId, name, barcode, pic, price, spec, unit, detailUrl, mkPrice;
		for (Li li : lis) {
			try {
				detailUrl = li.getA().getHref();// 详情地址
				proId = detailUrl.substring(detailUrl.indexOf("id=") + 3);// 商品Id
				pic = li.getA().getImg().getSrc();// 小图片路径(完整路径)
			} catch(Exception e) {// 可能没有链接
				detailUrl = null;
				proId = null;
				pic = li.getImg().getSrc();
			}
			
			name = li.getDiv().getPs().get(0).getB().getText();// 名称
			price = li.getDiv().getPs().get(1).getStrong().getSpan().getText();// 价格(如: 价格：¥20)
			price = price.replace("价格：¥", "");
			mkPrice = li.getDiv().getPs().get(1).getSpan().getText();// 市场价(如: ¥20)
			mkPrice = mkPrice.replace("¥", "");
			barcode = li.getDiv().getPs().get(2).getB().getText();// 条码
			spec = li.getDiv().getPs().get(3).getB().getText();// 规格
			// 只有一个斜杠时,认为最后一个为单位
			if (spec.split("/").length == 2) {
				unit = spec.substring(spec.indexOf("/") + 1);// 单位
			} else {
				unit = null;
			}
			
			
			if (!App.checkBarCode(barcode)) {
				System.out.println("条码无效: " + proId + " -> " + barcode + " -> "  + name);
				continue;
			}
			
			goodsInfo = new StringBuffer();
			goodsInfo.append("\r\nID:" + proId);
			goodsInfo.append("\r\n条码:" + barcode);
			goodsInfo.append("\r\n名称:" + name);
			goodsInfo.append("\r\n单位:" + unit);
			goodsInfo.append("\r\n规格:" + spec);
			goodsInfo.append("\r\n单价:" + price);
			goodsInfo.append("\r\n市场价:" + mkPrice);
			goodsInfo.append("\r\n小图:" + pic);
			goodsInfo.append("\r\n地址:" + detailUrl);
			System.out.println(goodsInfo);
			
			App.PicObject picObj = new App.PicObject();
			
			if (null != pic ) {
				App.setPic(pic, picObj);
			}
			
			if (!productRepository.exists(barcode)) {
				
				System.out.println("添加: " + barcode + " -> " + name);
				

				Product product = new Product();

				//product.setArea(items.getCountry());
				product.setBarcode(barcode);
				product.setBigPic(App.saveGoodsBigImageV1(picObj.getBigPic()));
				//product.setBrandName(brandName);
				//product.setCatName(catName);
				//product.setFacCode(items.getFacCode());
				//product.setFacName(items.getFacName());
				product.setIsCheckName(true);
				product.setMidPic(App.saveGoodsMiddleImageV1(picObj.getMidPic()));
				product.setName(name);
				//product.setSpell(rs.getString("pinyin"));
				product.setPic(App.saveGoodsImageV1(picObj.getPic()));
				product.setPrice(price);
				product.setUnit(unit);
				product.setSource("jgmall.cn");
				product.setSpec(spec);
				//product.setSupplier(items.getSupplier());
				product.setSysRemark(proId);

				productRepository.insert(product);

			} else {
				
				System.out.println("修改: " + barcode + " -> " + name);

				Product product = productRepository.findOne(barcode);

				if (null == product.getBigPic()) {
					product.setBigPic(App.saveGoodsBigImageV1(picObj.getBigPic()));
				}
				if (null == product.getMidPic()) {
					product.setMidPic(App.saveGoodsMiddleImageV1(picObj.getMidPic()));
				}
				if (null == product.getPic()) {
					product.setPic(App.saveGoodsImageV1(picObj.getPic()));
				}
				
				if (null != name && null == product.getName()) {
					product.setName(name);
				}
				if (null != price && null == product.getPrice()) {
					product.setPrice(price);
				}
				if (null != unit && null == product.getUnit()) {
					product.setUnit(unit);
				}
				if (null != spec && null == product.getSpec()) {
					product.setSpec(spec);
				}
				
				productRepository.save(product);

			}
			
			
		}
		
		return null;
	}
	
}
